/**  
 * All rights Reserved, Designed By www.beonelot.com
 * @Package: com.bccah.modlib.dbdo.controller
 * @Filename: AcsControlUserInfoController.java
 * @Description: TODO(AcsControlUserInfoController)
 * @author: 金鑫智慧
 * @date: 2020-04-08
 * @version: V1.0
 * @Copyright: 2018 www.beonelot.com Inc. All rights reserved.
 * 注意：本内容仅限于重庆金鑫智慧科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.jinxin.platform.cdacsrecord.core.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.*;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.CommonCodeEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.Constant;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.ResultEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.AcsControlUserInfoVO;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.DataResult;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.DataResult2;
import com.jinxin.platform.cdacsrecord.core.service.*;
import com.jinxin.platform.cdacsrecord.core.utils.IdCardUtil;
import com.jinxin.platform.cdacsrecord.core.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * TODO(AcsControlUserInfoController)
 * @Classn: AcsControlUserInfoController
 * @author SY
 * @date 2020-04-08
 */
@RestController
@RequestMapping("/basicUser")
@Slf4j
public class AcsControlUserInfoController {


    @Autowired
    private AcsControlUserInfoService userInfoService;
    @Autowired
    private AcsControlSysParamService paramService;
    @Autowired
    private IJurenICCardService icCardService;
    @Autowired
    private RestTemplateService restTemplateService;
    @Autowired
    private AcsExportService exportService;

    /**
     * 获取用户信息的分页表
     * @param userName
     * @param page
     * @param limit
     * @return
     */
    @PostMapping("/userTable")
    public Map getUserTable(String userType,String blockID,String roomId, String userName, int page, int limit, String community){
        Map<String,Object> resultMap = new HashMap<>();
        PageInfo<AcsControlUserInfoDO> pageInfo = userInfoService.selParamPage(page,limit,userType,blockID,roomId,userName,community,"", Constant.USER_TYPE_MEMBER);
        resultMap.put("code","0");
        resultMap.put("msg","");
        resultMap.put("count",pageInfo.getTotal());
        resultMap.put("data",pageInfo.getList());
        return resultMap;
    }

    @GetMapping("/memberTable")
    public Map getMemberTable(int page, int limit,String parentId, String companyId){
        Map<String,Object> resultMap = new HashMap<>();
        // 这里相当于先去聚人平台更新数据
//        List<AcsControlUserInfoDO> memebers =
//                restTemplateService.listMemebersById(parentId, companyId);
//        if(memebers != null && memebers.size() > 0){ // 有数据就直接返回
//            resultMap.put("code","0");
//            resultMap.put("msg","");
//            resultMap.put("count",memebers.size());
//            resultMap.put("data",memebers);
//            return resultMap;
//        }
        // 可能出现请求失败，就去数据库查询返回
        PageInfo<AcsControlUserInfoDO> pageInfo = userInfoService.selParamPage(page,limit,"","","","",companyId,parentId, "");
        long count = pageInfo.getTotal();
        List<AcsControlUserInfoDO> list = pageInfo.getList();
        resultMap.put("code","0");
        resultMap.put("msg","");
        resultMap.put("count",count);
        resultMap.put("data",list);
        return resultMap;
    }
    /**
     * 添加用户信息
     * @param infoVO
     * @return
     */
    @PostMapping("/addUser")
    public ResultEntity addUserInfo(MultipartFile file,@Valid AcsControlUserInfoVO infoVO) {
        log.info(infoVO.toString());
        Map<String,String> resMap = null;
        try {
            resMap = userInfoService.addAcsUser(infoVO,file);
            return new ResultEntity(resMap.get("resultCode"),resMap.get("resultDesc"),"" ) ;
        } catch (Exception e) {
            log.error("addUserInfo: ",e);
            return new ResultEntity(CommonCodeEntity.FAIL,"保存失败，请联系管理员","" );
        }

    }

    @PostMapping("/addMember")
    public ResultEntity addMemberInfo(MultipartFile file,AcsControlUserInfoVO infoVO) {
        log.info(infoVO.toString());
        Map<String,String> resMap = null;
        try {
            resMap = userInfoService.addMember(infoVO,file);
            return new ResultEntity(resMap.get("resultCode"),resMap.get("resultDesc"),"" ) ;
        } catch (Exception e) {
            log.error("addMemberInfo: ",e);
            return new ResultEntity(CommonCodeEntity.FAIL,"保存失败，请稍后重试","" );
        }

    }

    /**
     * 删除用户信息
     * @param bid
     * @return
     */
    @PostMapping("/delUser")
    public ResultEntity delUser(String bid,String companyId,String fafId){
        // 放进 service 处理，添加事物，同时删除 用户信息和访问类型信息
        Map<String,String> resMap = userInfoService.delAcsUser(bid,companyId,fafId);
        return new ResultEntity(resMap.get("resultCode"),resMap.get("resultDesc"),"" ) ;
    }

    @PostMapping("/delMember")
    public ResultEntity delMember(String uid,String companyId){
        Map<String,String> resMap = userInfoService.deleteMember(uid,companyId);
        return new ResultEntity(resMap.get("resultCode"),resMap.get("resultDesc"),"" ) ;
    }

//    /**
//     * 更新用户信息
//     * @param infoVO
//     * @return
//     */
//    @PostMapping("/upUserInfo")
//    public ResultEntity upUserInfo(@Valid AcsControlUserInfoVO infoVO){
//        if(StringUtils.isEmpty(infoVO.getUserId() )){
//            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"USER_ID为空","" );
//        }
//        AcsControlUserInfoDO infoDO = new AcsControlUserInfoDO();
//        BeanUtils.copyProperties(infoVO,infoDO );
//        log.info(infoDO.toString());
//        userInfoService.updateDO(infoDO);
//        return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","" );
//    }

    /**
     * 导入人员信息
     * @param file
     * @return
     */
    @PostMapping("/uploadUser")
    public ResultEntity uploadUser(MultipartFile file,String community) {
        if(file == null){
            return new ResultEntity(CommonCodeEntity.FAIL,"请选择文件上传","" );
        }
        if(StringUtils.isEmpty(community)){
            return new ResultEntity(CommonCodeEntity.FAIL,"小区未选择","" );
        }
        try {
            return userInfoService.uploadUser(file,community);
        } catch (Exception e) {
            log.error("error",e);
            return new ResultEntity(CommonCodeEntity.FAIL,"导入失败，请联系管理员","" );
        }
    }

    @RequestMapping("/exportUser2Excel")
    public void exportUser2Excel(HttpServletResponse response, String communityId){
        exportService.exportUser2Excel(response, communityId);
    }

    @PostMapping("/icCard/addOrEdit")
    public ResultEntity icCardOperate(JurenIcCardInfo icCardInfo){
        return icCardService.saveOrUpdate(icCardInfo);
    }

    @PostMapping("/icCard/cardStatus")
    public ResultEntity cardStatus(JurenIcCardInfo icCardInfo){
        return restTemplateService.cardStatus(icCardInfo);
    }

    @GetMapping("/icCard/list")
    public Map listAllCard(Integer page, Integer limit, JurenIcCardInfo icCardInfo){
        ResultEntity resultEntity = restTemplateService.listAllCard(page, limit, icCardInfo);
        Map<String,Object> resultMap = new HashMap<>();
        if(resultEntity.getResultCode().equals("000")){
            DataResult dataResult = (DataResult)resultEntity.getResultContent();
            List<JSONObject> jsonList = JSON.parseArray(dataResult.getRows().toString(),JSONObject.class);
            List<JurenIcCardInfo> dataList = new ArrayList<>();
            for (JSONObject json : jsonList) {
                JurenIcCardInfo cardInfo = JSON.parseObject(toJSONString(json), JurenIcCardInfo.class);
                dataList.add(cardInfo);
            }
            resultMap.put("count", dataResult.getRecords());
            resultMap.put("data", dataList);
        }
        resultMap.put("code","0");
        resultMap.put("msg","");
        return resultMap;
    }

    /**
     *
     * @param
     * @return
     */
    @PostMapping("/getUserById")
    public ResultEntity getUserById(String id){
        AcsControlUserInfoDO acsControlUserInfoDO = userInfoService.selById(id);
        return new ResultEntity("0","",acsControlUserInfoDO);

    }

    @RequestMapping("/syncData")
    public ResultEntity syncData(String companyId){
        int count = 0;
        int count2 = 0;
        try {
            // 这里一次性取10000，相当于取完，避免多次请求第三方接口可能失败的情况
            ResultEntity resultEntity = restTemplateService.wyOwnerYcSearch(1, 10000, companyId);
            if(resultEntity != null && resultEntity.getResultCode().equals("000")){
                DataResult2 dataResult = (DataResult2)resultEntity.getResultContent();
                if(dataResult == null){
                    return new ResultEntity(CommonCodeEntity.FAIL,"同步失败,请重试","" );
                }
                long total = dataResult.getRecords();
                if(total == 0){
                    return new ResultEntity(CommonCodeEntity.FAIL,"同步失败,请重试","" );
                }
                AcsControlUserInfoDO userParam = new AcsControlUserInfoDO();
                userParam.setCompanyId(companyId);
//                userParam.setExcludeType(Integer.parseInt(Constant.USER_TYPE_MEMBER));
                List<AcsControlUserInfoDO> list = userInfoService.selDOByInfo(userParam, "");
                List<String> idList = new ArrayList<>();
                for (AcsControlUserInfoDO record : list) {
                    idList.add(record.getUserId());
                }
                List<JSONObject> jsonList = JSON.parseArray(dataResult.getRows().toString(),JSONObject.class);
                for (JSONObject json : jsonList) {
                    OwnerUserInfo userInfo = JSON.parseObject(toJSONString(json), OwnerUserInfo.class);
                    if(userInfo != null){
//                        if(Constant.USER_TYPE_MEMBER.equals(userInfo.getUserType()+"")){
//                            continue;
//                        }
                        String oId = userInfo.getOId();
                        AcsControlUserInfoDO userInfoDO = userInfoService.selById(oId);
                        if(userInfoDO == null){
                            userInfoDO = new AcsControlUserInfoDO();
                            userInfoDO.setUserId(oId);
                            userInfoDO.setUserType(userInfo.getUserType()+"");
                            userInfoDO.setUserName(userInfo.getName());
                            userInfoDO.setUserName(userInfo.getName());
                            userInfoDO.setUserCardType("1");//身份证
                            String idCardNo = userInfo.getIdCardNo();
                            if(IdCardUtil.isValidatedAllIdcard(idCardNo)){
                                userInfoDO.setUserCard(idCardNo);
                                userInfoDO.setAge(Utils.getPersonAgeFromIdCard(idCardNo));
                            }
                            String userPhone = !StringUtils.isEmpty(userInfo.getPhone()) ? userInfo.getPhone() : "-";
                            userInfoDO.setUserPhone(userPhone);
                            userInfoDO.setUserBlockId(userInfo.getAreaId()+"");
                            userInfoDO.setUserRoomId(userInfo.getUnitAreaId()+"");
                            userInfoDO.setHushaiConsistent(0);//默认0人户一致
                            userInfoDO.setPartyMembership(1);//默认1群众
                            String detailRoomNo = userInfo.getDetailRoomNo();
                            String blockName = "";
                            if(!StringUtils.isEmpty(detailRoomNo) && detailRoomNo.contains("-")){
                                blockName = detailRoomNo.split("-")[0];
                            }
                            userInfoDO.setUserBlockName(blockName);
                            userInfoDO.setUserRoomName(detailRoomNo);
                            userInfoDO.setCreateTime(LocalDateTime.now());
                            userInfoDO.setState("0");
                            userInfoDO.setCompanyId(companyId);
                            userInfoDO.setGender(userInfo.getGender());
                            // TODO 暂时去掉人脸同步
                            try {
                                String[] idPathArr = restTemplateService.queryFaces(companyId, oId);
                                if(idPathArr != null){
                                    userInfoDO.setUserFingerprint(idPathArr[0]);
                                    userInfoDO.setUserFaceInfo(idPathArr[1]);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                            // TODO parentId 等接口开发完成
                            userInfoDO.setParentId(userInfo.getParentId());
                            userInfoService.saveDO(userInfoDO);
                            count++;
                        }else {
                            userInfoDO.setParentId(userInfo.getParentId());// 更新之前的数据
                            String idCardNo = userInfo.getIdCardNo();
                            if(IdCardUtil.isValidatedAllIdcard(idCardNo)){
                                userInfoDO.setAge(Utils.getPersonAgeFromIdCard(idCardNo));
                            }
                            userInfoService.updateDO(userInfoDO);
                            count2++;
                            idList.remove(oId);
                        }
                    }
                }
                // 删除不存在数据
                for (String id : idList) {
                    userInfoService.delDO(id);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ResultEntity(CommonCodeEntity.FAIL,"同步失败,请重试","" );
        }
        log.info("成功同步人员数据"+count+"条，更新"+count2+"条");
        return new ResultEntity(CommonCodeEntity.SUC_CODE,"成功同步人员数据"+count+"条，更新"+count2+"条","");
    }

}
